import React, { useState, useEffect } from 'react';
import StudentSearchBar from '../../components/StudentSearchBar/index';
import Pager from '../../components/Pager/index';
import StudentTable from '../../components/StudentTable/index';
import { searchStudents } from '../../services/student';
import qs from 'query-string';

function getQuery(search) {
    const queryDefault = {
        page: 1,
        limit: 10,
        key: '',
        sex: -1
    };
    let query = qs.parse(search);
    query = Object.assign({}, queryDefault, query);
    query.limit = +query.limit;
    query.page = +query.page;
    query.sex = +query.sex;
    return query;
    // return Object.assign({}, queryDefault, { limit: +query.limit, page: +query.page, sex: +query.sex });
    // return { ...queryDefault, ...query };
};

function useResult(query) {
    const [result, setResult] = useState({
        cont: 0,
        list: []
    });
    useEffect(() => {
        searchStudents({ ...query }).then(res => {
            console.log(res);
            setResult(res);
        })
    }, [query.limit, query.key, query.sex, query.page])
    return result;
};

function changeLocation(query, history) {
    console.log(query, history);
    const search = qs.stringify(query);
    history.push("?" + search);
}



export default function StudentList(props) {
    const query = getQuery(props.location.search);
    console.log(query)

    // const [tableData, setTableData] = useState([]);
    // const [total, setTotal] = useState(0);
    const result = useResult(query);

    function click(params) {
        console.log(params);
        props.history.push({
            pathname: `/students/${params.id}`,
            row: params
        });
    }

    return (
        <div>
            {/* <h1>学生列表页</h1> */}
            <StudentSearchBar defaultValue={{
                key: query.key,
                sex: query.sex
            }} onSearch={params => {
                console.log(params);
                const newQuery = {
                    ...query,
                    key: params.key,
                    sex: params.sex
                };
                changeLocation(newQuery, props.history);
            }} onReset={params => {
                console.log(params);
                const newQuery = {
                    ...query,
                    key: params.key,
                    sex: params.sex,
                    page: 1
                };
                changeLocation(newQuery, props.history);
            }} />
            <StudentTable data={result.list} handleClick={click} />
            <div>
                <Pager current={query.page} total={result.cont} limit={query.limit} panelNumber={5} onPageChange={newPage => {
                    const newQuery = {
                        ...query,
                        page: newPage
                    };
                    changeLocation(newQuery, props.history);
                }} />
            </div>
        </div>
    );
};
